<template>
  <!-- 第三方登录相关弹框  -->
  <div v-if="!isBind" class="container relative  mx-auto flex w-full h-full py-5 xl:py-0 xl:my-0 xl:w-6/12">
    <div
      :class="`${prefixCls}-form`"
      class="relative w-full px-5 py-8 mx-auto my-auto rounded-md shadow-md xl:ml-16 xl:bg-transparent sm:px-8 xl:p-4 xl:shadow-none sm:w-3/4 lg:w-2/4 enter-x"
    >
      <LoginFormTitle class="enter-x " :class="`${prefixCls}-title`"/>
      <ThirdBindUser ref="thirdBindUserRef"></ThirdBindUser>
    </div>
  </div>
  <Loading :loading="compState.loading"  :theme="compState.theme" :background="compState.background" :tip="compState.tip" />
  <LoginSelect ref="loginSelectRef" @success="handleLoginSelectOk" />
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick } from 'vue';
  import {  } from '/@/views/sys/login/useLogin';
  import { useRouter } from 'vue-router';
  import { PageEnum } from '/@/enums/pageEnum';
  import { router } from '/@/router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import ThirdBindUser from './ThirdBindUser.vue';
  import { thirdAuthLogin } from '/@/api/auth'
  import LoginFormTitle from './LoginFormTitle.vue';
  import { LoginStateEnum, useLoginState } from './useLogin';
  import { Loading } from '/@/components/Loading';
  import { useUserStore } from '/@/store/modules/user';
  import LoginSelect from './LoginSelect.vue';

  const { t } = useI18n()
  const { createMessage, notification } = useMessage()
  const userStore = useUserStore()
  const { setLoginState } = useLoginState();
  const env = ref<any>({ thirdApp: false, wxWork: false, dingtalk: false });
  const { currentRoute } = useRouter();
  const route = currentRoute.value;
  const thirdBindUserRef = ref();
  const isBind = ref(true)
  const loginSelectRef = ref<any>()
  const { prefixCls } = useDesign('bind-account');
  const authToken = ref<any>({})
  const queryParams = router.currentRoute.value.query
  const redirect = queryParams?.redirect as string || queryParams?.backUrl as string ||  PageEnum.BASE_HOME

  setLoginState(LoginStateEnum.THIRD_BIND)
  const compState = ref({
    absolute: false,
    loading: true,
    theme: 'dark',
    background: 'rgba(111,111,111,.7)',
    tip: '授权中...',
  });
  
  onMounted(async () => {
    window.document.title = '完善账号信息'
    env.value.thirdApp = true

    const thirdLoginParam = { ...route.params, ...route.query }
    console.log('thirdLoginParam: ', thirdLoginParam)
    thirdAuthLogin(thirdLoginParam).then(async data => {
      console.log('login-result: ', data)
      compState.value.loading = false
      isBind.value = data.isBind
      if (data.isBind) {
        authToken.value = data.authToken
        try {
          await loginSelectRef.value.show({
            accessToken: data.authToken.accessToken, 
            loginId: data.authToken.loginId
          })
        } catch(e) {
          goLoginPage()
        }
       
        return
      }
      nextTick(async () => {
        const success = await doOAuth2Login({ ...thirdLoginParam, ...data});
        if (!success) {
          console.log('授权失败')
          goLoginPage()
        }
      })
    }).catch(err => {
      console.error(err)
      goLoginPage()
    }).finally(e => {
      compState.value.loading = false
    })
   
  })

  function goLoginPage() {
    router.replace(`${PageEnum.BASE_LOGIN}?redirect=${redirect}`)
  }
  
  // 登录成功之后先跳出用户租户选择, 选择成功之后执行最后的登录逻辑
  function handleLoginSelectOk(userInfo : any, menuLoadingKey) {
    console.log('login success ', userInfo);
    try {
      if (userInfo) {
        setTimeout(() => {
          notification.success({
            message: t('sys.login.loginSuccessTitle'),
            description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realName}`,
            duration: 3,
          });
        }, 2000)
        userStore.afterLoginAction(true, { tenantId: userInfo.tenantId })
      }
    } finally {
      setTimeout(() => createMessage.destroy(menuLoadingKey), 500)
    }
  }

  /**
   * 进行OAuth2登录操作
   */
  async function doOAuth2Login(data) {
    if (env.value.thirdApp) {
      // 判断是否携带了Token，是就说明登录成功
      if (route.query.accessToken) {
        let token = route.query.accessToken;
        //执行登录操作
        thirdLogin({ token, thirdType: route.query.grantType });
      } else {
        return await thirdBindUserRef.value?.onThirdLogin(data)
      } 
    }
    return true
  }

  /**
   * 第三方登录
   * @param params
   */
  function thirdLogin(params) {
    const userStore = useUserStore();
    const { notification } = useMessage();
    const { t } = useI18n();
    userStore.ThirdLogin(params).then((res) => {

      if (res && res.userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${res.userInfo.realname}`,
          duration: 3,
        });
      } else {
        notification.error({
          message: '登录失败',
          description: ((res.response || {}).data || {}).message || res.message || '请求出现错误，请稍后再试',
          duration: 4,
        });
      }
    });
  }
</script>

<style lang="less">

  @prefix-cls: ~'@{namespace}-bind-account';

  .@{prefix-cls} {
    min-height: 100%;
    overflow: hidden;
    // @media (max-width: @screen-xl) {
    //   background-color: #293146;

    //   .@{prefix-cls}-form {
    //     background-color: #fff;
    //   }
    // }

    &-form {
      top: -20px;
      margin: auto;
      background-color: #fff;
      box-shadow: 0 4px 8px -4px rgba(0,0,0,.13), 0 6px 16px 0 rgba(0,0,0,.08), 0 12px 24px 16px rgba(0,0,0,.04);
    }

    &-title {
      font-size: 20px;
    }

    &::before {
      position: absolute;
      top: 0;
      left: 0;
      width: 80%;
      height: 100%;
      // margin-left: -48%;
      background-image: url(/@/assets/svg/login-bg.svg);
      background-position: 100%;
      background-repeat: no-repeat;
      background-size: auto 100%;
      content: '';
      @media (max-width: @screen-xl) {
        display: none;
      }
    }

    &-sign-in-way {
      .anticon {
        font-size: 22px;
        color: #888;
        cursor: pointer;

        &:hover {
          color: @primary-color;
        }
      }
    }

    input:not([type='checkbox']) {
      min-width: 360px;

      @media (max-width: @screen-xl) {
        min-width: 420px;
      }

      @media (max-width: @screen-lg) {
        min-width: 260px;
      }

      @media (max-width: @screen-md) {
        min-width: 240px;
      }

      @media (max-width: @screen-sm) {
        min-width: 160px;
      }
    }

    .valid-code input {
      min-width: auto;
    }

    .ant-divider-inner-text {
      font-size: 12px;
      color: @text-color-secondary;
    }
  }
</style>